package com.qf.smsplatform.strategy.strategy.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StragetyConstents;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: sms-platform
 *
 * @author: 黄睿武
 * time: 2021/8/13 19:40
 * description:
 */


/**
 * 扣费策略策略
 */
@Service(value = "fee")
@Slf4j
public class FeeStrategyImpl implements Strategy {

    @Autowired
    private CacheClient cacheClient;





    /**
     * 所有策略模块必须有的一个方法,用于校验或补全短信内容(submit对象)
     *
     * @param submit 短信内容
     * @return true代表通过, false校验未通过
     */
    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-扣费策略]  开始执行.......");
        //1.查询当前短信需要的费用
        long fee = submit.getFee();
        int clientID = submit.getClientID();

        //2.直接调用CacheClient的hincr命令,获得到扣除费用后的剩余金额
        Long remainFee = cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",-fee);

        //3.判断剩余金额是否小于0 (小于0则金额不足)
        if(remainFee < 0 ){
            //4.把预扣除的费用加回去
            cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",fee);

            //5.发送消息,返回flase

            //5.1发送日志
            PushErrorMessageUtil.sendLog(submit,StragetyConstents.STRATEGY_ERROR_FEE);
            //5.2状态报告
            Integer isreturnstatus = Integer.valueOf(cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "isreturnstatus"));
            if(isreturnstatus == 1){
                PushErrorMessageUtil.sendReport(submit,StragetyConstents.STRATEGY_ERROR_FEE);
            }

            log.info("[策略模块-扣费策略]  执行失败.......");
            return false;
        }


        //策略模块无法确定短信是否发送成功,到了网关模块才能确定消息是否发送成功
        log.info("[策略模块-扣费策略]  执行成功.......");
        return true;
    }
}
